package com.srwl.mytx.adapter;

import android.content.Context;
import android.graphics.RectF;
import android.media.MediaPlayer;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;

import com.bm.library.Info;
import com.bm.library.PhotoView;
import com.github.florent37.viewanimator.ViewAnimator;
import com.srwl.mytx.Constant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.domain.Message;
import com.srwl.mytx.utils.GlideLoadUtils;
import com.srwl.mytx.widget.MyVideoPlayer;

import java.io.File;
import java.util.List;


public class ChatFileShowAdapter extends PagerAdapter {
    private static final String TAG = "BigPictureAdapter";
    private final Context context;
    private final int screenHeight;
    private final int screenWidth;
    private List<Message> messageList;
    private InteractionListener listener;
    private Info info;//小图位置信息
    private boolean isFirstShow = true;
    private int animationPosition;//当前需要动画的item 选项，不能仅仅依靠 isFirstShow 来判断当前需要动画的 item ，
    private View currentView;
    private SurfaceHolder mSurfaceHolder;
    private MediaPlayer mMediaPlayer;

    public ChatFileShowAdapter(Context context, List<Message> messageList, InteractionListener listener) {
        this.context = context;
        this.messageList = messageList;
        this.listener = listener;
        screenHeight = context.getResources().getDisplayMetrics().heightPixels;
        screenWidth = context.getResources().getDisplayMetrics().widthPixels;
    }

    @Override
    public int getCount() {

        return messageList.size();
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view == object;
    }

    //不考这这个方法，notifyDateSetChange()无效
    @Override
    public int getItemPosition(Object object) {
        return POSITION_NONE;
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull final ViewGroup container, final int position) {
        final View view;
        Message message = messageList.get(position);
        if (Constant.IM_TYPE_IMAGE == message.getSubType()) {
            view = LayoutInflater.from(context).inflate(R.layout.tx_item_big_picture, null);

            final PhotoView photoView = view.findViewById(R.id.iv_picture);
            photoView.enable();
            photoView.setAnimaDuring(400);
            if (isFirstShow && animationPosition == position) {
                photoView.setVisibility(View.INVISIBLE);
            }
           // RequestOptions options = new RequestOptions().diskCacheStrategy(DiskCacheStrategy.ALL);
            //判断展示的文件是否为本地文件还是远程文件
            String localPath;
            if (!TextUtils.isEmpty(message.getLocalFilePath())) {
                //发送的消息
                localPath = message.getLocalFilePath();
            } else {
                //收到的消息，或者是一条  目前属于发送消息，但是其实是一条 转发于 收到的  消息
                String imageKey = message.getContent();
                localPath = Helper.getInstance().getFilePath() + File.separator + imageKey;
            }
           // Glide.with(context).asBitmap().load(localPath).apply(options).into(photoView);
            GlideLoadUtils.glideLoad(context,localPath,photoView);

            photoView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    listener.onItemClick(position);
                }
            });


            TextView tv_count = view.findViewById(R.id.tv_title);
            tv_count.setText((position + 1) + "/" + getCount());
        } else {

            MyVideoPlayer videoPlayer = new MyVideoPlayer(context);
            if (isFirstShow && position == animationPosition) {
                videoPlayer.setVisibility(View.INVISIBLE);
            }
            videoPlayer.ivBack.setOnClickListener(v -> listener.onItemClick(position));

            String videoPath;
            String localFilePath = message.getLocalFilePath();
            if (TextUtils.isEmpty(localFilePath)) {
                videoPath = Helper.getInstance().getFilePath() + File.separator + message.getContent();
            } else {
                //原始发送消息 或者 转发于某条 发送消息
                videoPath = localFilePath;
            }

            videoPlayer.init(videoPath, videoPath);
            videoPlayer.tvTitle.setText((position + 1) + "/" + getCount());
            view = videoPlayer;
        }


//        ImageView img_delete = view.findViewById(R.id.img_delete_picture);
//        img_delete.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                destroyItem(container, position, view);
//                listener.onItemRemove(position);
//            }
//        });
        container.addView(view);
        return view;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);

    }

    @Override
    public void setPrimaryItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        super.setPrimaryItem(container, position, object);
        if (currentView != object && currentView != null && currentView instanceof MyVideoPlayer) {
            MyVideoPlayer videoPlayer = (MyVideoPlayer) currentView;
            videoPlayer.pauseVideo();
        }

        currentView = (View) object;//获取当前显示的View,这样才能在按下返回键的时候，拿到photoView,显示缩小的动画
//        Object tag = currentView.getTag();
//        if (Constant.MY_FILE_TYPE_PICTURE == (int) tag) {
//            JzvdStd.resetAllVideos();
//        }
    }


    public void setAnimationPosition(int animationPosition, Info info) {
        this.animationPosition = animationPosition;
        this.info = info;
    }

    public void showAnimateIn(Info smallImageViewInfo) {
        if (currentView == null || smallImageViewInfo == null) {
            return;
        }
        if (currentView instanceof MyVideoPlayer) {

            currentView.setVisibility(View.VISIBLE);
            MyVideoPlayer videoPlayer = (MyVideoPlayer) currentView;
            videoPlayer.animateEnter(smallImageViewInfo);
//            Info bigImageViewInfo = PhotoView.getBigImageViewInfo(videoPlayer.ivCover);
//            RectF bigImageRectF = bigImageViewInfo.getmImgRect();

        } else {
            final PhotoView photoView = currentView.findViewById(R.id.iv_picture);
            photoView.setVisibility(View.VISIBLE);
            photoView.animaFrom(smallImageViewInfo);
            View rl_title = currentView.findViewById(R.id.container);
            ViewAnimator.animate(rl_title).alpha(0, 1).duration(400).start();
        }
        isFirstShow = false;
    }


    public void showAnimateOut(Info smallImageViewInfo) {
        if (smallImageViewInfo == null) {
            Log.e(TAG, "onClick: 获取小图消息失败 ");
            return;
        }

        if (currentView instanceof MyVideoPlayer) {

            MyVideoPlayer videoPlayer = (MyVideoPlayer) currentView;
            videoPlayer.stopVideo();
            videoPlayer.animateExit(smallImageViewInfo);

        } else {
            PhotoView photoView = currentView.findViewById(R.id.iv_picture);
            View rl_title = currentView.findViewById(R.id.container);

            //计算缩放 移动的值，用于标题栏的移动
            Info bigImageViewInfo = PhotoView.getBigImageViewInfo(photoView);
            if (bigImageViewInfo == null) {//必须要判空，图片加载失败的时候，就是空的
                return;
            }
            RectF bigImageRectF = bigImageViewInfo.getmImgRect();
            RectF smallRectF = smallImageViewInfo.getmImgRect();
            float scaleX = smallRectF.width() / bigImageRectF.width();
            float scaleY = smallRectF.height() / bigImageRectF.height();
            float translationY = bigImageViewInfo.getmRect().centerY() - smallImageViewInfo.getmRect().centerY();
            float translationX = bigImageViewInfo.getmRect().centerX() - smallImageViewInfo.getmRect().centerX();
            ViewAnimator.animate(rl_title)
                    .scaleX(scaleX).scaleY(scaleY).alpha(1, 0)
                    .translationY(0, -translationY).translationX(0, -translationX)
                    .duration(300)//动画执行时间设置为300 ，不能设置为400，不然会看起滞后于photoView的动画
                    .start();
            photoView.animaTo(smallImageViewInfo, new Runnable() {
                @Override
                public void run() {
                    //  reset();
                }
            });
            //  ViewAnimator.animate(currentView).scaleX(scaleX).scaleY(scaleY).translationY(0, -translationY).translationX(0, -translationX).duration(400).start(); //对整个View进行缩放，

        }
        isFirstShow = true;
    }


    public interface InteractionListener {

        void onItemClick(int position);

        void onItemRemove(int position);
    }
}
